import { VxeTablePropTypes } from '@xfchenju/vxe-table';

interface CustomList extends VxeTablePropTypes.MergeCell {
  name?: any;
}

type CellMergeMapType = Record<string, Record<number, { name: string; span: number }>>;

export const useCellRowMerge = () => {
  // 合并方法
  function handleCellMerge(data: any[], mergeFields: string[]) {
    const cellMergeMap: CellMergeMapType = {};
    for (let i = data.length - 1; i >= 0; i--) {
      const item = data[i];
      for (let j = 0; j < mergeFields.length; j++) {
        const field = mergeFields[j];
        if (!cellMergeMap[field]) {
          cellMergeMap[field] = {};
        }
        const last = cellMergeMap[field][i + 1];
        if (last && last.name === item[field]) {
          cellMergeMap[field][i] = {
            name: item[field],
            span: last.span + 1
          };
          last.span = 0;
        } else {
          cellMergeMap[field][i] = {
            name: item[field],
            span: 1
          };
        }
      }
    }
    return cellMergeMap;
  }

  // 将cellMerge（spanMethod）格式的转为 mergeCells格式的
  function handleTransformMapToList(
    cellMergeMap: CellMergeMapType,
    fieldToColMap: Record<string, number | number[]>
  ) {
    const list: CustomList[] = [];
    for (const i in cellMergeMap) {
      const item = cellMergeMap[i];
      const cols = fieldToColMap[i];
      for (const j in item) {
        const itemJ = item[j];
        if (typeof cols === 'number') {
          const cellItem = {
            row: Number(j),
            rowspan: itemJ.span,
            col: cols,
            colspan: 1
          };
          if (itemJ.span) {
            list.push(cellItem);
          }
        } else {
          cols.forEach(col => {
            const cellItem = {
              row: Number(j),
              rowspan: itemJ.span,
              col: col,
              colspan: 1
            };
            if (itemJ.span) {
              list.push(cellItem);
            }
          });
        }
      }
    }

    return list;
  }

  /**
   * 获取mergeCells格式的合并
   * @param data
   * @param mergeFields
   * @param fieldToColMap
   * @returns
   */
  function getMergeList(data: any[], fieldToColMap: Record<string, number | number[]>) {
    const mergeFields = Object.keys(fieldToColMap);
    const cellMergeMap = handleCellMerge(data, mergeFields);
    return handleTransformMapToList(cellMergeMap, fieldToColMap);
  }

  return {
    handleCellMerge,
    handleTransformMapToList,
    getMergeList
  };
};
